package com.nicolas.solr.client;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.LBHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;

public class SolrClient {

	private static final String serverurl = "http://localhost/solr/collection1";

	public void addIndex() {
		try {
			SolrServer server = new LBHttpSolrServer(serverurl);
			SolrInputDocument document = new SolrInputDocument();
			document.addField("id", "3458345678");
			document.addField("name", "大神啊，救救我吧");
			UpdateResponse response = server.add(document);
			System.out.println(response.getRequestUrl());
			server.commit();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String search() throws MalformedURLException {
		SolrServer server = new HttpSolrServer(serverurl);
		ModifiableSolrParams params = new ModifiableSolrParams();
		// 查询关键词
		params.set("q", "大");
		// 分页，，start=0就是从0开始，，rows=5当前返回5条记录，，，第二页就是变化start这个值为5就可以了。
		params.set("start", 0);
		params.set("rows", 5);
		// 排序，，如果按照id 排序，，那么将score desc 改成 id desc(or asc)
		params.set("sort", "score desc");
		// 返回信息 * 为全部 这里是全部加上score，如果不加下面就不能使用score
		params.set("fl", "*,score");
		try {
			QueryResponse response = server.query(params);
			SolrDocumentList docs = response.getResults();
			System.out.println("文档个数：" + docs.getNumFound());
			System.out.println("查询时间：" + response.getQTime() + "ms");
			System.out.println();
			for (Iterator iterator = docs.iterator(); iterator.hasNext();) {
				SolrDocument doc = (SolrDocument) iterator.next();
				System.out.println("id：" + doc.getFieldValue("id"));
				System.out.println("name：" + doc.getFieldValue("name"));
				System.out.println();
			}
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
		return "";

	}

	public static void main(String[] args) throws MalformedURLException,
			SolrServerException {
		SolrClient sc = new SolrClient();
		// sc.addIndex();
		sc.search();
	}
}
